﻿using System.Windows;
using System.Windows.Controls;
using SilverMindMap.Core.ViewModel;

namespace SilverMindMap.Core.View
{
    [TemplatePart(Name = "NodePresenter", Type = typeof(ContentPresenter))]
    public class NodeControl : Control
    {
        public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register(
            "ViewModel", typeof(NodeViewModel), typeof(NodeControl), new PropertyMetadata(null));

        public static readonly DependencyProperty PositionProperty = DependencyProperty.Register(
            "Position", typeof(Point), typeof(NodeControl), new PropertyMetadata(new Point(0, 0), OnPositionChanged));

        public static readonly DependencyProperty NodeTemplateProperty = DependencyProperty.Register(
            "NodeTemplate", typeof(DataTemplate), typeof(NodeControl), new PropertyMetadata(null));

        private static void OnPositionChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            ((NodeControl)sender).OnPositionChanged((Point)args.OldValue, (Point)args.NewValue);
        }

        public NodeControl()
        {
            this.DefaultStyleKey = typeof(NodeControl);
            this.SizeChanged += (s, a) => UpdateCanvasProperties();
        }

        public NodeViewModel ViewModel
        {
            get { return (NodeViewModel)GetValue(ViewModelProperty); }
            set { SetValue(ViewModelProperty, value); }
        }

        public Point Position
        {
            get { return (Point)GetValue(PositionProperty); }
            set { SetValue(PositionProperty, value); }
        }

        public DataTemplate NodeTemplate
        {
            get { return (DataTemplate)GetValue(NodeTemplateProperty); }
            set { SetValue(NodeTemplateProperty, value); }
        }

        protected virtual void OnPositionChanged(Point oldValue, Point newValue)
        {
            UpdateCanvasProperties();;
        }

        private void UpdateCanvasProperties()
        {
            var position = this.Position;
            Canvas.SetLeft(this, position.X - this.DesiredSize.Width / 2.0);
            Canvas.SetTop(this, position.Y - this.DesiredSize.Height / 2.0);
        }
    }
}
